package com.example.fail5.link2arduino;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.xpf.ch340_library.CH340Master;
import com.xpf.ch340_library.driver.InitCH340;
import com.xpf.ch340_library.inteface.CallBack;
import com.xpf.ch340_library.inteface.CallBackUtils;
import com.xpf.ch340_library.utils.CH340Util;

import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Main2Activity extends AppCompatActivity implements InitCH340.IUsbPermissionListener, CallBack {

    Button bt_top;
    Button bt_left;
    Button bt_right;
    Button bt_down;
    Button bt_clear;
    lattice lattice;
    PlusThread plusThread;
    public boolean isOnLongClick = false;
    private static final String ACTION_USB_PERMISSION = "com.linc.USB_PERMISSION";

    int  x=0;
    private boolean isFirst;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        CallBackUtils.setCallBack(this);
        initData();
        bt_top = findViewById(R.id.bt_top);
        bt_left = findViewById(R.id.bt_left);
        bt_right = findViewById(R.id.bt_right);
        bt_down = findViewById(R.id.bt_down);
        lattice = findViewById(R.id.lattice);
        bt_clear = findViewById(R.id.bt_clear);

        bt_top.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                isOnLongClick = true;
                try {
                    Thread.sleep(300);

                    myHandler.sendEmptyMessage(1);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        bt_left.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                lattice.xChange2X(false);
            }
        });


        bt_right.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                lattice.xChange2X(true);
            }
        });
        bt_down.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                lattice.xChange2Y(true);
            }
        });
        bt_clear.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                x=0;
            }
        });
        CompentOnTouch b = new CompentOnTouch();
        bt_down.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                plusThread = new PlusThread();
                plusThread.type = 1;
                isOnLongClick = true;
                plusThread.start();
                return false;
            }
        });
        bt_top.setOnTouchListener(b);
        bt_right.setOnTouchListener(b);
        bt_left.setOnTouchListener(b);
        bt_top.setOnTouchListener(b);
    }


    // Touch事件
    class CompentOnTouch implements View.OnTouchListener {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (v.getId()) {
                // 这里也写，是为了增强易点击性
                case R.id.bt_left:

                    onTouchChange(1, event.getAction());
                    break;
                case R.id.bt_right:
                    onTouchChange(2, event.getAction());
                    break;
                case R.id.bt_top:
                    onTouchChange(3, event.getAction());
                    break;
                case R.id.bt_down:

                    onTouchChange(4, event.getAction());
                    break;
                default:
                    break;

            }
            return true;
        }
    }


    // 加操作
    class PlusThread extends Thread {
        int type;

        @Override
        public void run() {
            while (isOnLongClick) {
                try {
                    Thread.sleep(300);

                myHandler.sendEmptyMessage(type);
                    super.run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    private void onTouchChange(int type, int eventAction) {
        // 按下松开分别对应启动停止减线程方法

        if (eventAction == MotionEvent.ACTION_DOWN) {
            plusThread = new PlusThread();
            plusThread.type = type;
            isOnLongClick = true;
            plusThread.start();
        } else if (eventAction == MotionEvent.ACTION_UP) {
            if (plusThread != null) {
                isOnLongClick = false;
            }
        } else if (eventAction == MotionEvent.ACTION_MOVE) {
            if (plusThread != null) {
                isOnLongClick = true;
            }
        }


    }

    @SuppressLint("HandlerLeak")
    Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            switch (msg.what) {

                case 1:
                    sendData();
                    lattice.xChange2X(false);
                    break;
                case 2:
                    sendData();
                    lattice.xChange2X(true);

                    break;
                case 3:
                    sendData();
                    lattice.xChange2Y(false);

                    break;
                case 4:
                    sendData();
                    lattice.xChange2Y(true);

                    break;

                case 0x102:
                    String receive = bundle.getString("aa");

                    receive = receive.trim();
                    if (String.valueOf(x).equals(receive)) {
                        isOnLongClick = true;
                    }

                    break;
                default:
                    break;
            }
        }
    };


    private void sendData() {


        if (isFirst&&isOnLongClick) {
            x=x+1;
            Log.d("Main2Activity", "x:" + x);
            byte[] bytes = CH340Util.toByteArray2("aaa22sss22222222222");
            CH340Util.writeData(bytes);

            isOnLongClick = false;
        }
    }

    private void initData() {
        InitCH340.setListener(this);
        if (!isFirst) {
            isFirst = true;
            // 初始化 ch340-library
            CH340Master.initialize(MyApplication.getContext());

        }
    }

    @Override
    public void result(boolean isGranted) {
        if (!isGranted) {
            PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
            InitCH340.getmUsbManager().requestPermission(InitCH340.getmUsbDevice(), mPermissionIntent);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter usbFilter = new IntentFilter();
        usbFilter.addAction(ACTION_USB_PERMISSION);
        registerReceiver(mUsbReceiver, usbFilter);
    }

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        if (device != null) {
                            Toast.makeText(Main2Activity.this, "EXTRA_PERMISSION_GRANTED~", Toast.LENGTH_SHORT).show();
                            InitCH340.loadDriver(MyApplication.getContext(), InitCH340.getmUsbManager());
                        }
                    } else {
                        Toast.makeText(Main2Activity.this, "EXTRA_PERMISSION_GRANTED null!", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mUsbReceiver);
    }

    @Override
    public void doSomeThing(String string) {
        Message message = new Message();
        message.what = 0x102;
        Bundle bundle = new Bundle();
        bundle.putString("aa", string);
        message.setData(bundle);
        myHandler.sendMessage(message);
    }

}
